package sch.frog.utils.math;

import java.util.List;

/**
 * 多边形工具
 */
public class PolygonUtil {
	
	public static class Point {
		public final double X;
		
		public final double Y;
		
		public Point(double x, double y) {
			X = x;
			Y = y;
		}
	}
	
	/**
	 * 判断一个点是否在多边形内部
	 * @param pt 待判断的点
	 * @param polygon	多边形
	 * @param noneZeroMode	如果点坐落在多边形内部的镂空区域, 是否算在多边形内部, true算, false不算
	 * @return
	 */
	public static boolean isWithin(Point pt, List<Point> polygon, boolean noneZeroMode) {
        int ptNum = polygon.size();
        if (ptNum < 3) {
            return false;
        }
        int j = ptNum - 1;
        boolean oddNodes = false;
        int zeroState = 0;
        for (int k = 0; k < ptNum; k++) {
            Point ptK = polygon.get(k);
            Point ptJ = polygon.get(j);
            if (((ptK.Y > pt.Y) != (ptJ.Y > pt.Y)) && (pt.X < (ptJ.X - ptK.X) * (pt.Y - ptK.Y) / (ptJ.Y - ptK.Y) + ptK.X)) {
                oddNodes = !oddNodes;
                if (ptK.Y > ptJ.Y) {
                    zeroState++;
                }
                else {
                    zeroState--;
                }
            }
            j = k;
        }
        return noneZeroMode?zeroState!=0:oddNodes;
    }
}
